<?php

namespace App\Services\BuyVip;

use App\Models\User;
use App\Models\Coupon;
use App\Models\VipCategory;
use App\Models\Address;
use App\Models\Product;
use App\Models\VipWelfareDetail;
use App\Models\UserWelfareRecord;
use App\Models\VipWelfareDetailRelationCoupon;
use App\Services\MakeProductOrder\MakeProductOrder;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;

class BuyVip
{
    protected User $user;

    protected int $vip_price = 0;

    public function __construct(User $user,  $vip_category_id = null,$vip_purchase_id =null ,Address $address,array $items = [])
    {
        $this->user = $user;
        $this->vip_price = $this->getVipCategory($vip_category_id)->price_lowest;
        $this->vip_day = $this->getVipCategory($vip_category_id)->day;
        $this->price_brokerage = $this->getVipCategory($vip_category_id)->price_brokerage;
        $this->vip_category_id = $vip_category_id;
        $this->address = $address;
        $this->items = $items;
        $this->vip_purchase_id =$vip_purchase_id;
       
    }

    public function getVipCategory($id)
    {
        return VipCategory::find($id);

    }

    protected function execute()
    {
        DB::transaction(function ()  {
           
            
           $this->purchase = $this->user->vipPurchases()->create([
                'total_amount' => $this->vip_price,
                'status' => 'pending',
                'vip_category_id' => $this->vip_category_id,
            ]);

            foreach($this->items as $k=>$v){
                $res = VipWelfareDetail::find($v['welfare_detail_id']);
                if($res->type=="coupon"){
                     $this->user->welfareRecords()->create([
                        'vip_welfare_detail_id' => $v['welfare_detail_id'],
                        'vip_purchase_id' =>  $this->purchase->id
                    ]);
                }elseif($res->type=="phone"){
                     $this->user->welfareRecords()->create([
                        'vip_welfare_detail_id' => $v['welfare_detail_id'],
                        'phone' => $v['phoneNumber'],
                        'vip_purchase_id' =>  $this->purchase->id
                    ]);
                }else{
                    $this->user->welfareRecords()->create([
                        'vip_welfare_detail_id' => $v['welfare_detail_id'],
                        'product_id' => $v['product_id'],
                        'address_id' => $this->address->id,
                        'vip_purchase_id' =>  $this->purchase->id
                    ]);

                }
            }
        });

        return $this->purchase; 
    }

    public function buy()
    {
        return $this->execute();
    }

    protected function items($product)
    {
        return [[
            'sku_id' => $product->skus()->first()->id,
            'amount' => 1
        ]];
    }

    public function bought()
    {

        $vipPeriod = Carbon::now()->addDays($this->vip_day);

        if($this->user->isValidVip()){

            if (!empty($this->user->vip_expired_at) && Carbon::now()->lte($this->user->vip_expired_at)) {
                $vipPeriod = Carbon::parse($this->user->vip_expired_at)->addDays($this->vip_day);
            } 
        }



        DB::transaction(function () use($vipPeriod) {
            

            $welfareRecords = UserWelfareRecord::query()->where('vip_purchase_id',$this->vip_purchase_id)->get()->toArray();

            foreach($welfareRecords as $value){
                 $res = VipWelfareDetail::find($value['vip_welfare_detail_id']);
                 if($res->type == 'coupon'){
                    $coupon = VipWelfareDetailRelationCoupon::query()->where('vip_welfare_detail_id',$value['vip_welfare_detail_id'])->get()->toArray();

                    foreach($coupon as $k=>$v){
                        $day =  Coupon::find($v['coupon_id']);
                        for($i=0;$i<$v['number'];$i++){
                            
                            $this->user->coupons()->create([
                              'coupon_id' => $v['coupon_id'],
                              'destory_at' => Carbon::now()->addDays($day->day)
                           ]);
                        }

                    }

                 }elseif($res->type=='phone'){


                 }else{
                  $order = app(MakeProductOrder::class, [
                        'user' => $this->user,
                        'address' => Address::find($value['address_id']),
                        'items' => $this->items(Product::find($value['product_id'])),
                        'attr' => null,
                        'order' => null,
                        'isFree' => 1
                    ])->make();

                 }
            }
            
            $this->user->update([
                'grade' => 'vip',
                'vip_expired_at' => $vipPeriod,
            ]);

            if($this->user->parent_id){
                $parentUser = User::find($this->user->parent_id);
                account_brokerages($parentUser)->vipPaid($this->price_brokerage, []);

            }
        });

    }
}
